import React, { useCallback, useEffect, useRef, useState } from 'react'
import { View, Text, Image } from '@tarojs/components'
import Images from '@ASSET/Images'
import CommonList from '@COMPONENTS/List/CommonList'
import { getHighlightHtml } from '@UTILS/highlight'
import api from '@API'
import Taro from '@tarojs/taro'
import debounce from 'lodash.debounce'
import './SearchPredictions.scss'

export default function SearchPredictions({
  language, onClickPrediction, showPredictions, st
}) {
  const [showSt, setShowSt] = useState(st)
  const [predictionData, setPredictionData] = useState([])
  const fetchPredictions = useCallback(async (st, show) => {
    try {
      if (!show) return
      if (!st) {
        setPredictionData([])
        return
      }
      const { Predictions } = await api.getSearchPredictions({
        st,
        skip: 0,
      })
      setShowSt(st)
      setPredictionData(Predictions)
    } catch (error) {
      Taro.showToast({
        icon: 'none',
        title: error.message || error
      })
    }
  }, [])
  const debouncedFetchPredictions = useRef(debounce((text, show) => fetchPredictions(text, show), 1000))

  useEffect(() => {
    debouncedFetchPredictions.current(st, showPredictions)
  }, [fetchPredictions, showPredictions, st])
  const renderItem = useCallback((item, index) => {
    const highlight = [showSt]
    const text = item?.[language]
    const highlightHtml = getHighlightHtml(text, highlight)
    return (
      <View className="prediction-item" onClick={() => { onClickPrediction(text) }} key={index}>
        <Image src={Images.search} className="searchIcon" />
        <Text className="prediction-text">
          {highlightHtml}
        </Text>
      </View>
    )
  }, [language, onClickPrediction, showSt])
  if (!predictionData?.length || !showPredictions) {
    return null
  }
  return (
    <View className="searchPrediction">
      <CommonList
        showFooter={false}
        renderItem={renderItem}
        data={predictionData}
        refresherEnabled={false}
        backgroundColor="#FFFFFF"
      />
    </View>
  )
}
